﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;

namespace NexTrackDesktop.Media
{
    /// <summary>
    /// This class holds all cached album art
    /// </summary>
    public class ThumbnailCache
    {
        Dictionary<Uri, Uri> CachedFiles;
        Random r = new Random();

        /// <summary>
        /// This method creates a new cache for album art
        /// </summary>
        public ThumbnailCache()
        {
            CachedFiles = new Dictionary<Uri, Uri>();
        }

        /// <summary>
        /// This method caches remote album art to local address
        /// </summary>
        /// <param name="remote">Remote Uri to album art</param>
        /// <returns>Local cached copy of album art</returns>
        public Uri LocalCache(Uri remote)
        {
            if (!CachedFiles.ContainsKey(remote))
            {
                Uri local = new Uri(Path.GetTempFileName());
                CachedFiles[remote] = null;
                BeginDownload(remote, local);
            }

            return CachedFiles[remote];
        }

        /// <summary>
        /// This method begins downloading remote album art to local address
        /// </summary>
        /// <param name="remote"></param>
        /// <param name="local"></param>
        private void BeginDownload(Uri remote, Uri local)
        {
            ThreadStart downloadStart = new ThreadStart(
                delegate()
                {
                    new WebClient().DownloadFile(remote, local.LocalPath);

                    lock (this.CachedFiles)
                    {
                        CachedFiles[remote] = local;
                    }

                    OnDownloadComplete(remote);
                });

            new Thread(downloadStart).Start();
        }

        public void OnDownloadComplete(Uri remoteUri)
        {
            if (DownloadComplete != null)
                DownloadComplete(remoteUri);
        }

        public event Action<Uri> DownloadComplete;
    }
}
